﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace Proyecto_Ajedrez.Objects
{
    class Encryption
    {
        private TripleDESCryptoServiceProvider service;

        public Encryption(String key)
        {
            service = new TripleDESCryptoServiceProvider();
            service.Key = TruncateHash(key, service.KeySize / 8);
            service.IV = TruncateHash("", service.BlockSize / 8);
        }

        private Byte[] TruncateHash(String key, int length)
        {
            SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
            Byte[] keyBytes = System.Text.Encoding.Unicode.GetBytes(key);
            Byte[] hash = sha1.ComputeHash(keyBytes);

            Byte[] result = new Byte[length];
            for (int i = 0; i < length && i < hash.Length; i++)
                result[i] = hash[i];
            return result;
        }

        public String EncryptData(String text)
        {
            Byte[] plainText = System.Text.Encoding.Unicode.GetBytes(text);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, service.CreateEncryptor(), CryptoStreamMode.Write);

            cs.Write(plainText, 0, plainText.Length);
            cs.FlushFinalBlock();

            return Convert.ToBase64String(ms.ToArray());
        }

        public String DecryptData(String text)
        {
            Byte[] encryptedBytes = Convert.FromBase64String(text);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, service.CreateDecryptor(), CryptoStreamMode.Write);

            cs.Write(encryptedBytes, 0, encryptedBytes.Length);
            cs.FlushFinalBlock();

            return System.Text.Encoding.Unicode.GetString(ms.ToArray());
        }
    }
}
